﻿using SPCoder.FileSystem.Utils.Nodes;
using SPCoder.Utils;
using SPCoder.Utils.Nodes;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SPCoder.FileSystem.Utils
{
    public class FSConnector : BaseConnector
    {

        public FSConnector(string connectorType)
        { }

        public FSConnector()
        { }

        public override SPCoder.Utils.Nodes.BaseNode GetSPStructure(string siteUrl)
        {
            DirectoryInfo folder = new DirectoryInfo(siteUrl);
            BaseNode rootNode = new FolderNode(folder);

            TraverseFileSystem(folder, rootNode, rootNode);

            return rootNode;
        }

        private void TraverseFileSystem(DirectoryInfo folder, BaseNode parentNode, BaseNode rootNode)
        {
            try
            {
                //if (myNode == null)
                BaseNode myNode = new FolderNode(folder);

                if (parentNode != null)
                {
                    parentNode.Children.Add(myNode);
                    myNode.ParentNode = parentNode;
                }
                myNode.RootNode = rootNode;
                
                try
                {
                    foreach (DirectoryInfo d in folder.GetDirectories())
                    {
                        TraverseFileSystem(d, myNode, rootNode);
                    }
                }
                catch (Exception exc)
                {
                    //SPCoderForm.MainForm.LogException(exc);
                }


                foreach (FileInfo file in folder.GetFiles())
                {                    
                    BaseNode myFileNode = new FileNode(file);
                    myNode.Children.Add(myFileNode);
                    myFileNode.ParentNode = myNode;
                    myFileNode.RootNode = rootNode;
                    Icon icon = Icon.ExtractAssociatedIcon(file.FullName);
                    myFileNode.IconObject = icon.ToBitmap();
                    if (myFileNode.IconObject.Width != 16)
                    {
                        myFileNode.IconObject = new Bitmap(myFileNode.IconObject, 16, 16);
                    }                    
                }
            }
            catch (Exception exc)
            {
                //SPCoderForm.MainForm.LogException(exc);
            }
        }

        public override string ImagesPath
        {
            get
            {
                return null;
            }
            set
            {}
        }

        public override bool IsImagesPathLocal
        {
            get
            {
                return true;
            }
            set
            {}
        }
    }
}
